package com.magicsoft.app.wcf;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.boyuan.huijiaoyu.R;
import com.example.nearby.NearbyCenter;
import com.example.nearby.NearbyPeople;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.magicsoft.app.entity.HomeCenterEntity;
import com.magicsoft.app.entity.MapDataResp;
import com.magicsoft.app.entity.MapListResp;
import com.magicsoft.app.helper.TokenHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.constant.Constant;

public class MapService extends BaseService {

	private static final String MAP_SERVICE = "MapService";

	// public static String CAS_DOMAIN = "http://114.119.7.170:8081/";// cas平台地址

	public MapService(Context context) {
		// TODO Auto-generated constructor stub

		super(context);

	}

	// 获取附近中心
	public void getNearByPeopleService(String uid, double lat, double lng,
			final GetOneRecordListener<List<NearbyPeople>> listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.NEARBYPEOPLE + getParamString + "&uid="
				+ uid + "&location=" + lng + "%2C" + lat + "&radius=1000";

		Log.e(MAP_SERVICE, "requestUrl =" + requestUrl);
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {

				super.onSuccess(statusCode, headers, response);
				try {
					Log.e(MAP_SERVICE, "response =" + response.toString());
					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONArray contentArray = response
								.getJSONArray("content");

						List<NearbyPeople> result = new ArrayList<NearbyPeople>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<NearbyPeople>>() {
							}.getType();
							List<NearbyPeople> datas = gson.fromJson(
									contentArray.toString(), contentType);

							result.addAll(datas);
						}

						if (listener != null) {
							listener.onFinish(result);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
								// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {

				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/*
	 * 获取首页红点信息
	 */

	public void getHomeRedPoint(String uid,
			final GetOneRecordListener<List<HomeCenterEntity>> listener) {
		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.BIGDATA_CENTER + getParamString + "&uid="
				+ uid;
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);

				try {
					String code = response.getString("code");
					if ("0".equals(code)) {
						JSONArray contentArray = response
								.getJSONArray("content");

						List<HomeCenterEntity> result = new ArrayList<HomeCenterEntity>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<HomeCenterEntity>>() {
							}.getType();
							List<HomeCenterEntity> datas = gson.fromJson(
									contentArray.toString(), contentType);

							result.addAll(datas);
						}

						if (listener != null) {
							listener.onFinish(result);
						}
					} else {
						if (listener != null) {
							String message = response.getString("message");
							listener.onFailed(message);
						}
					}

				} catch (Exception e) {

					if (listener != null)

						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});
	}

	/**
	 * 获取地图数据
	 */
	public void getMapList(String branch_id, String uid,
			final GetOneRecordListener<List<MapListResp>> listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.BIGDATA_BRANCH + getParamString + "&cid="
				+ branch_id + "&uid=" + uid;

		Log.e("getMapList", requestUrl);

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);

				try {
//					Log.e("getMapList", response.toString());
					String code = response.getString("code");

					if ("0".equals(code)) {
						JSONArray contentArray = response
								.getJSONArray("content");

						List<MapListResp> result = new ArrayList<MapListResp>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<MapListResp>>() {
							}.getType();
							List<MapListResp> datas = gson.fromJson(
									contentArray.toString(), contentType);

							result.addAll(datas);
						}

						if (listener != null) {
							listener.onFinish(result);
						}
					} else {
						if (listener != null) {
							String message = response.getString("message");
							listener.onFailed(message);
						}
					}

				} catch (Exception e) {

					if (listener != null)

						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/**
	 * 获取地图数据
	 */
	public void getMapDatas(String branch_id, String year,
			final GetOneRecordListener<MapDataResp> listener) {

		// RequestParams params = new RequestParams();
		// params.put("d", "cpi");
		// params.put("m", "appNumber");
		// params.put("where", "branch_id=" + branch_id);

		// String requestUrl = Constant.BIGDATA + "?d=kpi&where=branch_id="
		// + branch_id + "-year=" + year;

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.BIGDATA_KPI + getParamString + "&branch="
				+ branch_id + "&year=" + year;

		Log.i("getMapDatas", requestUrl);

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);

				try {
					Log.i("getMapDatas", response.toString());

					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONObject contentObject = response
								.getJSONObject("content");
						MapDataResp result = new MapDataResp();
						if (response.toString().length() > 5) {

							Type accountType = new TypeToken<MapDataResp>() {
							}.getType();
							MapDataResp mapDataResp = gson.fromJson(
									contentObject.toString(), accountType);

							result = mapDataResp;
						}

						if (listener != null) {
							listener.onFinish(result);
						}
					}
				} catch (Exception e) {

					if (listener != null)

						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/**
	 * 百度坐标转换为高德坐标
	 */
	public void conversionCoordinate(List<MapListResp> datas,
			final GetOneRecordListener<String> listener) {

		StringBuffer buffer = new StringBuffer();

		for (int i = 0; i < datas.size(); i++) {
			MapListResp mapListResp = datas.get(i);
			buffer.append(mapListResp.getLng());
			buffer.append(",");
			buffer.append(mapListResp.getLat());
			if (i != datas.size() - 1) {
				buffer.append(";");
			}
		}

		String requestUrl = "http://restapi.amap.com/v3/assistant/coordinate/convert?locations="
				+ buffer.toString()
				+ "&coordsys=baidu&output=json&key=f22873710c5b49e90c4766b593c8de5e";

		Log.i("conversionCoordinate", requestUrl);

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);

				try {
					Log.i("conversionCoordinate", response.toString());
					String code = response.getString("status");
					String message = response.getString("info");
					if ("1".equals(code)) {
						String locations = response.getString("locations");

						if (listener != null) {
							listener.onFinish(locations);
						}
					}

				} catch (Exception e) {

					if (listener != null)

						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}
}
